//
//  BDFriendsListViewController.m
//  iOS_beboy
//
//  Created by wen on 2018/1/30.
//  Copyright © 2018年 com.8xiong. All rights reserved.
//

#import "BDFriendsListViewController.h"
#import "UIViewController+SearchController.h"
#import "BDUserModel.h"
#import "BDFridentTableViewCell.h"
#import "BDUserInfoViewController.h"
#import "BDNewFriendViewController.h"
#import "BDGroupListViewController.h"
#import <JMessage/JMessage.h>
#import "PinYin4Objc.h"

@interface BDFriendsListViewController ()<UITableViewDelegate, UITableViewDataSource, EMSearchControllerDelegate>
{
    NSUInteger _lastContactsHash;
}
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableDictionary *datasource;

@property (strong, nonatomic) NSMutableArray *indexList;    // 存放右侧索引
@property (nonatomic, strong) NSMutableArray *searchResultDatasource;
@end

@implementation BDFriendsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"好友列表");
    
    self.indexList = [NSMutableArray array];
    self.datasource = [NSMutableDictionary dictionary];
    
    [self bindRAC];
    
    [self getLocalFriendsAction];
    
    [self setupSearchController];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)bindRAC{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"resreshFriendsList" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [self.datasource removeAllObjects];
        [self.indexList removeAllObjects];
        [self getLocalFriendsAction];
    }];
}

- (void)setupSearchController{
    self.hidesNavigationBarDuringPresentation = YES;
    [self enableSearchController];
    __block BDFriendsListViewController *weafSelf = self;
    self.resultController.numberOfRowsInSectionCompletion = ^NSInteger(UITableView *tableView, NSInteger section) {
        return weafSelf.searchResultDatasource.count;
    };
    
    self.resultController.cellForRowAtIndexPathCompletion = ^(UITableView *tableView, NSIndexPath *indexPath) {
        BDFridentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        if (cell == nil) {
            cell = [[BDFridentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaa"];
        }
        BDUserModel *user = weafSelf.searchResultDatasource[indexPath.row];
        cell.nameLabel.text = user.nickname;
        [cell.avatarImage sd_setImageWithURL:[NSURL URLWithString:user.cover] placeholderImage:[UIImage imageNamed:@"avatar"]];
        cell.applyCountLabel.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    };
    
    self.resultController.heightForRowAtIndexPathCompletion = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
        return 60.0;
    };
    
    self.resultController.didSelectRowAtIndexPathCompletion = ^(UITableView *tableView, NSIndexPath *indexPath) {
        BDUserModel *curr_user = weafSelf.searchResultDatasource[indexPath.row];
        BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:curr_user.user_id isFollow:NO guanzhuBlock:nil];
        [weafSelf.navigationController pushViewController:userVC animated:YES];
    };
}

#pragma mark - UITableViewDataSource
//以下是添加删除功能的代码
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ASLocalizedString(@"删除好友");
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"deletedFriendModel"];
        
        
//        BDFridentInfo *delFriend = [self.datasource[self.indexList[indexPath.section - 1]] objectAtIndex:indexPath.row];
//        [[EMClient sharedClient].contactManager deleteContact:[NSString stringWithFormat:@"%@", delFriend.user_id] isDeleteConversation:YES];
//        //清理本地好友
//        [BDFMDBTool deleteWithObject:delFriend];
//        BDFridentInfo *newFriend = [BDFridentInfo mj_objectWithKeyValues:delFriend.mj_keyValues];
//
//        NSString *zhidingSearchPath = [DocumentPath stringByAppendingPathComponent:@"zhidingSearch.plist"];
//        NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:zhidingSearchPath];
//        [array removeObject:newFriend.user_id];
//        [array writeToFile:zhidingSearchPath atomically:YES];
//
//        NSString *miandaraoSearchPaths = [DocumentPath stringByAppendingPathComponent:@"miandaraoSearch.plist"];
//        NSMutableArray *miandaraoArray = [NSMutableArray arrayWithContentsOfFile:miandaraoSearchPaths];
//        [miandaraoArray removeObject:newFriend.user_id];
//        [miandaraoArray writeToFile:miandaraoSearchPaths atomically:YES];
//
//        NSMutableArray *curLitArray = self.datasource[self.indexList[indexPath.section - 1]];
//        [curLitArray removeObjectAtIndex:indexPath.row];
//        [self.tableview beginUpdates];
//        if (curLitArray.count == 0) {
//            //            [self.datasource removeObject:curLitArray];
//            [self.indexList removeObjectAtIndex:indexPath.section - 1];
//            [self.tableview deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
//        }
//        [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
//
//        [self.tableview endUpdates];
    }
    else if (editingStyle ==UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.indexList count] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }else{
        return [self.datasource[self.indexList[section - 1]] count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDFridentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDFridentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.avatarImage.image = [UIImage imageNamed:@"new_tianjia"];
            cell.nameLabel.text = ASLocalizedString(@"申请与通知");
            NSInteger unApplyFriendCount = 0;
//            NSArray *array = [BDFMDBTool queryWithClass:[BDApplyFriendsModel class]];
//            for (BDApplyFriendsModel *appleFriend in array) {
//                if ((appleFriend.applyMode.integerValue == BDApplyFriendModeDefault || appleFriend.applyMode.integerValue == BDApplyFriendModeDelete) && appleFriend.yetToView.integerValue == 0) {
//                    unApplyFriendCount++;
//                }
//            }
            if (unApplyFriendCount == 0) {
                cell.applyCountLabel.hidden = YES;
            }else{
                cell.applyCountLabel.hidden = NO;
                cell.applyCountLabel.text = [NSString stringWithFormat:@"%zd", unApplyFriendCount];
            }
        }else{
            cell.avatarImage.image = [UIImage imageNamed:@"qun_touxiang"];
            cell.nameLabel.text = ASLocalizedString(@"我的群聊");
            cell.applyCountLabel.hidden = YES;
        }
    }else{
        JMSGUser *fridentInfo = [self.datasource[self.indexList[indexPath.section - 1]] objectAtIndex:indexPath.row];
        cell.nameLabel.text = fridentInfo.nickname;
        [cell.avatarImage sd_setImageWithURL:[NSURL URLWithString:fridentInfo.avatar] placeholderImage:[UIImage imageNamed:@"avatar"]];
        cell.applyCountLabel.hidden = YES;
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else{
        return _indexList[section - 1];
    }
}
//添加tableview 右侧索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _indexList;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index
{
    //因为多一个section 所以要 +1
    return index + 1;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            BDNewFriendViewController *newFridentVC = [[BDNewFriendViewController alloc]init];
            [self.navigationController pushViewController:newFridentVC animated:YES];
        }else{
            //进入群列表
            BDGroupListViewController *groupList = [[BDGroupListViewController alloc] init];
            [self.navigationController pushViewController:groupList animated:YES];
        }
    }else{
        //
        
//        BDFridentInfo *friend = [self.datasource[self.indexList[indexPath.section - 1]] objectAtIndex:indexPath.row];
//        BDUserModel *user = [BDUserModel creatWithFriendInfo:friend];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpToNewChatVC" object:user];
        //        BDChatViewController *chatVC = [[BDChatViewController alloc] initWithConversationChatter:friend.user_id conversationType:EMConversationTypeChat];
        //        chatVC.title = friend.nickname;
        //        [self.navigationController pushViewController:chatVC animated:YES];
    }
}

#pragma mark - EMSearchControllerDelegate

- (void)searchTextChangeWithString:(NSString *)aString{
    if ([aString isNotEmpty]) {
        self.startPage = @"1";
        NSString *url = [NSString stringWithFormat:@"%@users?page=%@&&size=%@&type=1&keyword=%@&no_need_friends=0", KBDBaseURL, self.startPage, self.pageSize, aString];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            self.searchResultDatasource = [BDUserModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
            [self.resultController.tableView reloadData];
            self.startPage = x[@"next_page"];
            self.isEnd = [x[@"is_end"] boolValue];
            
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
            // BDLog(ASLocalizedString(@"搜索失败，错误是：%@"), error);
        }];
    }
}

#pragma mark 加载本地好友数据
-(void)getLocalFriendsAction{
    [MBManager showLoadingAlert:@"" clickHidden:NO clickBlock:nil];
    [JMSGFriendManager getFriendList:^(id resultObject, NSError *error) {
        if (error) {
            
        }else{
            
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSArray *friendArray = (NSArray *)resultObject;
                
                dispatch_semaphore_t sema = dispatch_semaphore_create(0);
                for (JMSGUser *friendInfo in friendArray) {
                    
                    NSString *userId = [friendInfo.username stringByReplacingOccurrencesOfString:@"beboy_" withString:@""];
                    if (userId.integerValue <= 100 && userId.integerValue != 7) {
                        continue;
                    }
                    
                    HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
                    [outputFormat setToneType:ToneTypeWithoutTone];
                    [outputFormat setVCharType:VCharTypeWithV];
                    [outputFormat setCaseType:CaseTypeLowercase];
                    
                    [PinyinHelper toHanyuPinyinStringWithNSString:friendInfo.nickname withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) {
                        NSString *firstLetter = [[pinYin substringToIndex:1] uppercaseString];
                        BOOL isLetter = [self matchLetter:firstLetter];
                        
                        NSString *key = firstLetter;
                        if (isLetter == NO) {
                            key = @"#";
                        }
                        
                        //如果数组中没有这个索引，那么在数组中加入这个索引
                        if (![self.indexList containsObject:key]) {
                            //                    NSLog(ASLocalizedString(@"添加了key：%@"), key);
                            [self.indexList addObject:key];
                        }
                        //根据索引取字典中的数组
                        NSMutableArray *litArray = self.datasource[key];
                        //如果字典为空，创建该字典
                        if (litArray == nil) {
                            litArray = [NSMutableArray array];
                            [self.datasource setObject:litArray forKey:key];
                        }
                        //将名字加入字典
                        [litArray addObject:friendInfo];
                        dispatch_semaphore_signal(sema);
                    }];
                    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
                }
                
                //将字母排序
                //        NSLog(ASLocalizedString(@"开始排序的时候内部元素数量：%zd"), self.indexList.count);
                [self.indexList sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    return obj1 > obj2;
                }];
                
                for (NSString *key in self.indexList) {
                    NSMutableArray *litArr = self.datasource[key];
                    [litArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                        JMSGUser *fr1 = (JMSGUser *)obj1;
                        JMSGUser *fr2 = (JMSGUser *)obj2;
                        return [fr1.nickname compare:fr2.nickname];
                    }];
                }
                
                if (self.indexList.count) {
                    //判断第一个是不是字母，如果不是放到最后一个
                    BOOL isLetter = [self matchLetter:self.indexList[0]];
                    if (!isLetter) {
                        //获取数组的第一个元素
                        NSString *firstStr = [self.indexList firstObject];
                        //移除第一项元素
                        [self.indexList removeObjectAtIndex:0];
                        //插入到最后一个位置
                        [self.indexList insertObject:firstStr atIndex:self.indexList.count];
                    }
                }
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableview reloadData];
                    [MBManager hideAlert];
                });
                
            });
            
        }
    }];
    
}


- (BOOL)matchLetter:(NSString *)str {
    //判断是否以字母开头
    NSString *ZIMU = @"^[A-Za-z]";
    NSPredicate *regextestA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ZIMU];
    
    if ([regextestA evaluateWithObject:str] == YES)
        return YES;
    else
        return NO;
}

- (UITableView *)tableview{
    if (!_tableview) {
        self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableview.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
        _tableview.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableview.backgroundColor = [UIColor clearColor];
        _tableview.tableHeaderView = self.searchController.searchBar;
        
        [self.view addSubview:_tableview];
    }
    return _tableview;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
